<template>
  <el-dialog
    v-model="centerDialogVisible"
    title="下载报告"
    width="500"
    align-center
    @close="closeDialog"
  >
    <div v-if="canDownload" class="" style="font-size: 14px">
      <div style="color: #333">请点击下载报告。</div>
      <div style="color: #888">
        (注：如遇浏览器拦截无法下载，请选择允许下载。)
      </div>
    </div>
    <div v-else class="" style="font-size: 14px; margin-bottom: 30px">
      <div
        v-if="isLoading"
        v-loading="isLoading"
        style="width: 100%; height: 50px"
      ></div>
      <div style="color: #333; text-align: center; margin-top: 20px">
        报告正在生成中,大约需要1～3分钟。
      </div>
    </div>

    <template #footer>
      <div v-if="canDownload" class="dialog-footer">
        <el-button type="primary" @click="downloadData(1, false)"
          >下载图片</el-button
        >
        <el-button type="primary" @click="downloadData(2, false)"
          >下载PDF</el-button
        >
      </div>
    </template>
  </el-dialog>
  <!-- 判断是否会员 -->
  <isVipDialog ref="isVipDialogShow" />
</template>
<script setup>
import { useStore } from 'vuex';
const store = useStore();
import isVipDialog from '@/components/Dialog/isVipDialog';
import { ref, computed } from 'vue';
import { getJudgImgSave } from '@/api/ping/ping';
import { ElMessage } from 'element-plus';
import axios from 'axios';
const prop = defineProps({
  ciPingStutas: {
    type: Object,
    default: () => {},
  },
});
const centerDialogVisible = ref(false);
const isVipDialogShow = ref(null);

const judgeInfo = ref({}); // 存储报告信息
const isLoading = ref(false); // 加载状态
const canDownload = ref(true); // 是否允许下载
let pollingInterval = null; // 轮询定时器

const safeCiPingStutas = computed(() => prop.ciPingStutas || []);

// 点击下载报告按钮
const downloadData = async (type) => {
  // 启动加载状态

  const isVIP = store.getters.user.userInfo.isVIP;
  // 当前用户状态
  if (isVIP <= 0) {
    if (
      (safeCiPingStutas.value.type == 1 &&
        !safeCiPingStutas.value?.checkList.includes('2')) ||
      (safeCiPingStutas.value.type == 2 && isVIP <= 0)
    ) {
      isVipDialogShow.value.openDialog();
      return;
    }
  } else {
    isLoading.value = true;
  }

  // 定义下载报告的文件名
  const fileName = type === 2 ? '测评报告.pdf' : '测评报告.jpg';
  const data = {
    id: judgeInfo.value.id,
    type,
  };
  // 定义轮询函数
  const pollDownloadData = async () => {
    try {
      const res = await getJudgImgSave(data, { timeout: 120000 });

      if (res.data && res?.data.code == 20000) {
        // 如果接口返回了有效的下载链接
        if (res.data.data?.url) {
          isLoading.value = false; // 结束加载状态
          canDownload.value = true; // 显示下载按钮
          clearInterval(pollingInterval); // 停止轮询
          await downloadBlob(res.data.data.url, fileName); // 下载文件
        }
      } else if (res.code == 400333) {
        // 如果接口返回 400333，表示报告还在生成中，继续轮询
        isLoading.value = true;
        canDownload.value = false; // 隐藏下载按钮
      }
    } catch (error) {
      console.error('下载失败:', error);
      isLoading.value = false;
    }
  };

  // 每20秒轮询一次，直到获得有效的下载链接
  pollingInterval = setInterval(pollDownloadData, 20000);

  // 初始化轮询，立即执行一次
  await pollDownloadData();
};
// 传统方法下载
const donloadPDF = async (url, fileName) => {
  const blob = await fetch(url).then((res) =>
    res.ok ? res.blob() : Promise.reject(res),
  );
  console.log(axios, url, fileName, blob);
  const urlObject = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = urlObject;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    window.URL.revokeObjectURL(urlObject);
    document.body.removeChild(a);
  }, 0);
  ElMessage({ message: '下载成功', type: 'success' });
};

// 新方法方法下载
const donloadPDFNew = async (url) => {
  // window.location.href = url;
  // const link = document.createElement('a');
  // link.href = url;
  // link.download = 'file.pdf'; // 指定下载文件名
  // link.target = '_blank'; // 避免当前页跳转
  // document.body.appendChild(link);
  // link.click();
  // document.body.removeChild(link);
  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      const blobUrl = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = blobUrl;
      let timer = new Date().getTime();
      link.download = timer + '.pdf';
      link.click();
      URL.revokeObjectURL(blobUrl);
    });
  ElMessage({ message: '下载成功', type: 'success' });
};

// 下载 Blob 数据
const downloadBlob = async (url, fileName) => {
  try {
    let a = 0;
    if (a > 1) {
      donloadPDF(url, fileName);
    } else {
      donloadPDFNew(url);
    }
  } catch (error) {
    console.log('下载失败:', error);
  }
};

// 打开弹窗时的处理函数
const openChange = async (val) => {
  judgeInfo.value = val;
  canDownload.value = true; // 打开弹窗时默认允许下载
  centerDialogVisible.value = true;
};

// 关闭弹窗时停止轮询
const closeDialog = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval); // 关闭轮询
  }
  isLoading.value = false; // 停止加载状态
  centerDialogVisible.value = false;
};

defineExpose({
  openChange,
});
</script>
<style lang="scss" scoped></style>
